package com.example.demo.job;

import com.example.demo.job.jobs.JobRepairOrder;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

@Slf4j
@Component
public class JobFactory {
    @Autowired
    JobRepairOrder jobRepairOrder;
    @Autowired
    JobFactoryConfiguration jobFactoryConfiguration;

    private Map<String, JobBase> map = new HashMap<>();

    @PostConstruct
    public void init() throws Exception {
        List<JobBase> jobList = new ArrayList<>();
        jobList.add(jobRepairOrder);

        if (jobList != null && jobList.size() > 0) {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            //add by qlx 添加jobfactory
            scheduler.setJobFactory(jobFactoryConfiguration);
            scheduler.start();

            for (JobBase job : jobList) {
                JobConfig jobConfig = job.getJobConfig();
                JobDetail jobDetail = newJob(job.getClass())
                        .withIdentity(jobConfig.getJobName(), jobConfig.getJobGroupName())
                        .build();
                CronTrigger cronTrigger = newTrigger()
                        .withIdentity(jobConfig.getTriggerName(), jobConfig.getTriggerGroupName())
                        .withSchedule(cronSchedule(jobConfig.getCron()))
                        .build();
                Date ft = scheduler.scheduleJob(jobDetail, cronTrigger);

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
                log.info("quartz-job:" + jobDetail.getKey()
                        + " turn on at: " + sdf.format(ft)
                        + "，the cron is: "
                        + cronTrigger.getCronExpression());
            }

        }
    }
}
